<template>
  <div>
    <form action="/">
      <van-search
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
      />
    </form>
    <div class="search">
      <p>大家都在搜</p>
      <button>长生修仙：从辅修开始</button>
      <button>青城山下三块石</button>
      <button>别叫我国医</button>
      <button>全职高手</button>
      <button>我在历史中长生不死</button>
    </div>
    <div>
      <p>
        搜索历史
        <span class="clear" @click="clear">清空历史记录</span>
      </p>
      <ul>
        <li v-for="(item, index) in historyList" :key="index">
          {{ item }}
        </li>
      </ul>
    </div>
    <div class="list" v-show="show">
      <van-card
        v-for="(item, index) in searchList"
        :key="index"
        :price="item.price"
        :desc="item.word"
        :title="item.title"
        :thumb="item.src"
      />
    </div>
  </div>
</template>
<script>
import { Toast } from 'vant'
import axios from 'axios'
export default {
  data() {
    return {
      value: '',
      list: [],
      searchList: [],
      historyList: [],
      show: false,
    }
  },
  mounted() {
    if (JSON.parse(localStorage.getItem('historyList'))) {
      this.historyList = JSON.parse(localStorage.getItem('historyList'))
    }
  },
  methods: {
    onSearch(val) {
      Toast(val)
    },
    onCancel() {
      Toast('取消')
    },
    async getList() {
      let resp = await axios.get('/api/list')
      this.list = resp.data.list
    },
    clear() {
      if (confirm('你确定要清空历史记录吗？')) {
        localStorage.removeItem('historyList')
        this.$router.go(0)
      }
    },
    onSearch() {
      if (this.value == '') {
        return false
      } else {
        if (this.historyList.includes(this.value)) {
          this.historyList.unshift(this.value)
          localStorage.setItem('historyList', JSON.stringify(this.historyList))
          console.log(this.historyList)
        } else {
          let i = this.historyList.indexOf(this.value)
          this.historyList.splice(i, 1)
          this.historyList.unshift(this.value)
          localStorage.setItem('historyList', JSON.stringify(this.historyList))
        }
      }
    },
    onInput(val) {
      console.log(val)
      if (this.value == '') {
        this.show = false
      } else {
        this.show = true
        this.searchList = this.list.filter((v) => {
          return v.title.indexOf(this.value) >= 0
        })
        console.log(this.searchList)
      }
    },
  },
  created() {
    this.getList()
  },
}
</script>
<style lang="scss">
.search {
  width: 100%;
  margin: 10px 20px;
  p {
    font-size: 16px;
    font-weight: bold;
  }
  button {
    margin: 10px 10px;
  }
}
</style>
